from __future__ import absolute_import
import os
from forest.registry import register_tool
from forest.tool import Tool
import logging
#from forest.tools.system.mount import mount

logger = logging.getLogger('forest.tools.system.chroot')

@register_tool('system.chroot')
class chroot(object):
    ''' A context manager which changes the current root.

        For example::

            with chroot('path'):

                ...
    '''
    def __init__(self, root, dir = None):
        self.root = root
        self.dir = '/' if dir is None else dir


    def __enter__(self):
        logger.info( 'Change root: %s', self.root)
        self.realdir = os.getcwd()
        self.realroot = os.open('/', os.O_RDONLY)

        os.chroot(self.root)
        os.chdir(self.dir)

        return self


    def __exit__(self, type, value, traceback):
        os.fchdir(self.realroot)
        os.chroot('.')
        #umount(os.path.join(self.root, 'dev'), lazy=True)
        os.close(self.realroot)
        os.chdir(self.realdir)

        logger.info( 'Exit root: %s', self.root)
